<?php

namespace App\Http\Controllers;


use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class UserController extends Controller
{
  public function __construct()
  {
      $this->middleware('auth', [
          'except' => ['show', 'create', 'store', 'index', 'confirmEmail']
      ]);
      //只让未登录用户访问注册页面
      $this->middleware('guest', [
          'only' => ['create']
      ]);
  }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $users=User::paginate(10);
        return view('users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {

        return view('users.create');
    }

    /**
     * 注册新用户.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserCreateRequest $request)
    {
        $user=User::create([
            'name'=>$request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);
        //注册成功后自动登陆
        //Auth::login($user);
        //发送激活邮件
        $this->sendEmail($user);
        session()->flash('success', '欢迎，您将在这里开启一段新的旅程~');
        return redirect()->route('users.show',[$user]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user=User::find($id);
        $statuses=$user->statuses()
            ->orderBy('created_at','desc')
            ->paginate(10);
        return view('users.show',compact('user','statuses'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user=User::findOrFail($id);

        //添加policy权限认证，当前用户不能操作别人的信息
        $this->authorize('update', $user);

        return view('users.edit',compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserUpdateRequest $request, $id)
    {
        $user=User::findOrFail($id);
        //添加policy权限认证，当前用户不能操作别人的信息
        $this->authorize('update', $user);
        $data=[];
        $data['name']=$request->name;
        //存在，并且不为空
        if($request->filled('password')){
            $data['password'] = bcrypt($request->password);
        }
        $user->update($data);
        session()->flash('success', '个人资料更新成功！');
        return redirect()->route('users.show',[$user]);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user=User::findOrFail($id);
        //验证是否登陆并且是管理员
        $this->authorize('destroy',$user);
        $user->delete();
        session()->flash('success', '成功删除用户！');
        return back();
    }

    public function confirmEmail($token)
    {
        $user = User::where('activation_token', $token)->firstOrFail();
        $user->activated = true;
        $user->activation_token = null;
        $user->save();
        Auth::login($user);
        session()->flash('success', '恭喜你，激活成功！');
        return redirect()->route('users.show', [$user]);
    }

    public function sendEmail($user)
    {
        $view = 'emails.confirm';
        $data = compact('user');
        $from = 'sangjia@163.com';
        $name = 'sangjia';
        $to = $user->email;
        $subject = "感谢注册 Weibo 应用！请确认你的邮箱。";
        Mail::send($view, $data, function ($message) use ($from, $name, $to, $subject){
            $message->from($from, $name)->to($to)->subject($subject);
        });

    }

    /*
     * 我的粉丝
     */
    public function followers(User $user)
    {
        $users=$user->followers()->paginate(20);
        $title = $user->name . '的粉丝';
        return view('users.show_follower',compact('users','title'));
    }

    /*
     * 我关注的用户
     */
    public function followings(User $user)
    {
        $users=$user->followings()->paginate(20);
        $title = $user->name . '关注的人';
        return view('users.show_follower',compact('users','title'));
    }

}
